import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_business_2003a/bean/home_banner_bean_result.dart';
import 'package:flutter_business_2003a/bean/home_hot_goods_bean_result.dart';
import 'package:flutter_business_2003a/bean/home_navigator_bean_result.dart';
import 'package:flutter_business_2003a/bean/home_recommend_bean_result.dart';
import 'package:flutter_business_2003a/service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  initState() {
    _getHotGoods();
    super.initState();
  }

  //用于页面更新
  int size = 10;
  List<HomeHotGoodsBean?> hotGoodsList = [];

  //火爆专区的标题
  Widget hotTitle = Container(
    margin: const EdgeInsets.only(top: 10.0),
    padding: const EdgeInsets.all(5.0),
    alignment: Alignment.centerLeft,
    decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
    child: const Text(
      '火爆专区',
      style: TextStyle(color: Colors.pink),
    ),
  );

  //火爆专区的WarpList(瀑布流)
  Widget _hotWrapList() {
    if (hotGoodsList.isNotEmpty) {
      List<Widget> listItemWidget = hotGoodsList.map((e) {
        return InkWell(
          onTap: () {
            print('点击了火爆专区的单品');
          },
          child: Container(
            width: ScreenUtil().setWidth(372).toDouble(),
            color: Colors.white,
            padding: const EdgeInsets.all(5.0),
            margin: const EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: [
                Image.network(
                  e!.goods_default_icon!,
                  width: ScreenUtil().setWidth(375).toDouble(),
                ),
                Text(
                  e.goods_desc!,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink,
                      fontSize: ScreenUtil().setSp(26).toDouble()),
                ),
                Text('团购价:¥${e.goods_default_price}元'),
                Text(
                  '原价:¥${e.goods_default_price}元',
                  style: const TextStyle(
                      color: Colors.black26,
                      decoration: TextDecoration.lineThrough),
                )
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2,
        children: listItemWidget,
      );
    } else {
      return const Center(
        child: Text('加载中'),
      );
    }
  }

  //火爆专区的组合
  Widget _hotGoods() {
    return Column(
      children: [hotTitle, _hotWrapList()],
    );
  }

  void _getHotGoods() {
    var formData = {'category_id': 24, 'currentPage': 1, 'pageSize': size};
    request('homeHotGoods', formData).then((value) {
      List<HomeHotGoodsBean?> newList =
          HomeHotGoodsBeanResult.fromJson(value).data![0]!.goodsInfoList!;
      setState(() {
        hotGoodsList.addAll(newList);
        size += 10;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334); //Iphone6的尺寸基准,设计图尺寸
    return Scaffold(
        appBar: AppBar(
          title: const Text('百姓生活+'),
        ),
        body: EasyRefresh(
          onRefresh: () async {},
          onLoad: () async {
            _getHotGoods();
          },
          footer: ClassicalFooter(
              bgColor: Colors.white,
              textColor: Colors.pink,
              infoColor: Colors.pink,
              showInfo: true,
              infoText: '加载中',
              loadReadyText: '上拉加载',
              loadedText: '加载完成',
              loadingText: '正在加载',
              loadText: '上拉加载'),
          header: ClassicalHeader(
              bgColor: Colors.white,
              textColor: Colors.pink,
              infoColor: Colors.pink,
              showInfo: true,
              noMoreText: '',
              infoText: '刷新中',
              refreshReadyText: '下拉刷新',
              refreshedText: '刷新完成',
              refreshingText: '正在刷新',
              refreshText: '下拉刷新'),
          child: ListView(
            children: [
              FutureBuilder(
                future: request('homePageBanner', null),
                builder: (context, val) {
                  if (val.hasData) {
                    List<HomeBannerBean?>? homeBannerList =
                        HomeBannerBeanResult.fromJson(val.data).data;
                    return SwiperDiy(swiperDataList: homeBannerList);
                  } else {
                    return const Center(
                      child: Text('加载中...'),
                    );
                  }
                },
              ),
              FutureBuilder(
                  future: request('homeNavigator', null),
                  builder: (context, val) {
                    if (val.hasData) {
                      List<HomeNavigatorBean?>? homeNavigatorList =
                          HomeNavigatorBeanResult.fromJson(val.data).data;
                      return HomeNavigator(navigatorList: homeNavigatorList);
                    } else {
                      return const Center(
                        child: Text('加载中...'),
                      );
                    }
                  }),
              FutureBuilder(
                  future: request('homeRecommend', null),
                  builder: (context, val) {
                    if (val.hasData) {
                      List<HomeRecommendBean?>? homeRecommendList =
                          HomeRecommendBeanResult.fromJson(val.data)
                              .data![0]
                              ?.goodsInfoList!;
                      return HomeRecommend(recommendList: homeRecommendList);
                    } else {
                      return const Center(
                        child: Text('加载中...'),
                      );
                    }
                  }),
              _hotGoods()
            ],
          ),
        ));
  }

  @override
  bool get wantKeepAlive => true;
}

//轮播图
class SwiperDiy extends StatelessWidget {
  final List<HomeBannerBean?>? swiperDataList;

  const SwiperDiy({Key? key, required this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: ScreenUtil().setWidth(333).toDouble(),
      child: Swiper(
        itemCount: swiperDataList!.length,
        itemBuilder: (context, index) {
          return Image.network(
            swiperDataList![index]!.imagePath!,
            fit: BoxFit.fill,
          );
        },
        pagination: const SwiperPagination(), //控制轮播图的小圆点
        autoplay: true, //是否自动轮播
      ),
    );
  }
}

//导航栏
class HomeNavigator extends StatelessWidget {
  const HomeNavigator({Key? key, required this.navigatorList})
      : super(key: key);

  final List<HomeNavigatorBean?>? navigatorList;

  //girdView的item布局
  Widget _girdViewItemUI(context, HomeNavigatorBean item) {
    return InkWell(
      //无涟漪效果的图片按钮
      onTap: () {
        print('点击了导航:${item.id}');
      },
      child: Column(
        children: [
          Image.network(
            '${item.giftpath}',
            width: ScreenUtil().setWidth(75).toDouble(),
            height: ScreenUtil().setHeight(75).toDouble(),
          ),
          Text('${item.price}')
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(270).toDouble(),
      padding: const EdgeInsets.all(3.0),
      child: GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: 6,
        padding: const EdgeInsets.all(4.0),
        children:
            //拿到数据集合后,将它(navigatorList)遍历(map),把其中每一个数值(e)赋值给UI的item,再形成一个集合(toList)
            navigatorList!.map((e) => _girdViewItemUI(context, e!)).toList(),
      ),
    );
  }
}

//商品推荐组件
class HomeRecommend extends StatelessWidget {
  final List<HomeRecommendBean?>? recommendList;

  const HomeRecommend({Key? key, required this.recommendList})
      : super(key: key);

  //商品推荐的标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: const BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: const Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //商品推荐的Item
  Widget _item(HomeRecommendBean item) {
    return InkWell(
      onTap: () {},
      child: Container(
        height: ScreenUtil().setHeight(300).toDouble(),
        width: ScreenUtil().setWidth(250).toDouble(),
        padding: const EdgeInsets.all(8.0),
        decoration: const BoxDecoration(
            color: Colors.white,
            border:
                Border(left: BorderSide(width: 1.0, color: Colors.black12))),
        child: Column(
          children: [
            Image.network(item.goods_default_icon!),
            Text('¥${item.goods_default_price}元'),
            Text(
              '¥${item.goods_default_price}元',
              style: const TextStyle(
                  decoration: TextDecoration.lineThrough, color: Colors.grey),
            )
          ],
        ),
      ),
    );
  }

  //商品推荐横向列表组件
  Widget _recommendList() {
    return SizedBox(
      height: ScreenUtil().setHeight(330).toDouble(),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _item(recommendList![index]!);
        },
        itemCount: recommendList!.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(385).toDouble(),
      margin: const EdgeInsets.only(top: 10.0),
      child: Column(
        children: [_titleWidget(), _recommendList()],
      ),
    );
  }
}
